package com.basin.micro.auth.mq.consumer;

import com.basin.micro.auth.module.account.service.AccountService;
import com.rabbitmq.client.Channel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author: Sam ZHONG | sammy1997@aliyun.com
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class AdminConsumer {
    private final AccountService accountService;

    /* 创建交换机、队列等
    @Resource
    private RabbitMqDynamicConfigService rabbitMqDynamicConfigService;

    @PostConstruct
    private void init() {
        rabbitMqDynamicConfigService.create(
                new RabbitMqBindingConfig() {{
                    setExchangeName("auth_exchange");
                    setRoutingKey("emp_init_authorized");
                    setQueueName("emp_auth_queue");
                    setExchangeTypeEnum(ExchangeTypeEnum.DIRECT);
                }}
        );
    }
     */
    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue("emp_auth_queue"),
                    exchange = @Exchange(value = "auth_exchange"),
                    key = "emp_init_authorized"
            )
    })
    public void receive(String empId, Message message, Channel channel) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            log.info("Received message: {}", empId);
            this.accountService.initEmpAccountAuth(empId);
            channel.basicAck(deliveryTag, true);
        } catch (Exception e) {
            log.error("Receive message error: {}", e.getMessage());
            channel.basicNack(deliveryTag, false, true);
        }
    }
}
